import json
import base64
import time
from django.shortcuts import render
from django.views import View
# Create your views here.
from django_redis import get_redis_connection

from apps.goods.models import SKU
from apps.users.models import User
from django.http import JsonResponse, HttpResponse


class UserPhoneCount(View):
    def get(self,request,phone):
        count=User.objects.filter(mobile=phone).count()
        return JsonResponse({"code":0,"count":count})



class RegisterView(View):
    def post(self,request):
        json_str=request.body
        json_str.decode()
        req_data=json.loads(json_str)
        username=req_data.get('username')
        mobile=req_data.get('mobile')
        verify=req_data.get('verify')
        password=req_data.get('password')
        count=User.objects.filter(mobile=mobile).count()
        if count>0:
            return JsonResponse({'code':0,'errmsg':'手机号重复，请更换'})
        if not verify:
            return JsonResponse({'code':400,'errmsg':'请同意协议'})
        if not all([mobile,password]):
            return JsonResponse({'code':400,'errmsg':'信息为空'})
        user=User.objects.create_user(mobile=mobile,password=password,username=username)
        from django.contrib.auth import login
        login(request,user)
        return JsonResponse({'code':0,'errmsg':'成功'})


class LoginView(View):
    def post(self,request):
        json_str=request.body
        json_str.decode()
        req_data=json.loads(json_str)
        # mobile=req_data.get('mobile')
        password=req_data.get('password')
        username=req_data.get('username')
        user=User.objects.filter(username=username,password=password)
        from django.contrib.auth import  authenticate
        user=authenticate(username=username,password=password)
        if user is None:
            return JsonResponse({'code':400,'errmsg':'手机号或密码错误'})
        from django.contrib.auth import login
        login(request,user)
        request.session.set_expiry(0)
        response=JsonResponse({'code':0,'errmsg':'成功登录'})
        response.set_cookie('username',username)
        return response

class EditView(View):
    def put(self,request):
        try:
            user=request.user
        except:
            return JsonResponse({'code':400,'err':'用户未登录'})
        data=json.loads(request.body.decode())
        # 头像
        img_header = data.get('img_header')
        if img_header:
            ines = img_header.split('base64,')
            imgData = base64.b64decode(ines[1])
            timestamp = str(int(time.time()))
            file_url1 = 'media/%s.%s' % (timestamp, 'jpg')
            img = file_url1
            leniyimg = open(file_url1, 'wb')
            leniyimg.write(imgData)
            leniyimg.close()
        else:
            img = ''
        # 其他个人信息
        nickname=data.get('nickname')
        gender=int(data.get('gender'))
        qq_num=data.get('qq_num')
        ballage=int(data.get('ballage'))
        self_intro=data.get('intro')

        # if not all([nickname,gender,qq_num,ballage,self_intro]):
        #     return JsonResponse({'code': 400, 'errmsg': '信息为空'})
        update_msg=User.objects.filter(username=user.username).update(img_header=img,nickname=nickname,sex_gender=gender,qq_num=qq_num,ball_age=ballage,intro=self_intro)
        return JsonResponse({'code':0,'errmsg':'ok'})
from django.contrib.auth import logout
class LogoutView(View):
    def delete(self,request):
        logout(request)
        response =JsonResponse({'code':0,'errmsg':'ok'})
        response.delete_cookie('username')
        return response

# 判断用户是否登陆，重写方法使得返回JSON数据
from django.contrib.auth.mixins import AccessMixin,LoginRequiredMixin
class LoginRequiredJsonMixin(LoginRequiredMixin):
    def handle_no_permission(self):
        return JsonResponse({'code':400,'errmsg':'用户未登录'})

#改变邮箱地址
class EmailView(LoginRequiredJsonMixin,View):
    def put(self,request):
        json_str=request.body
        json_str.decode()
        data=json.loads(json_str)
        email=data.get('email')
        user=request.user
        user.email=email
        user.save()
        return JsonResponse({'code':0,'errmsg':'修改成功'})


class InfoView(LoginRequiredJsonMixin,View):
    def get(self,request):
        info_data={
            'username':request.user.username,
            'email':request.user.email,
            'mobile':request.user.mobile,
            'email_active':request.user.email_active,
            'nickname':request.user.nickname,
            'img_header':str(request.user.img_header),
            'gender':request.user.sex_gender,
            'qq_num':request.user.qq_num,
            'ball_age':request.user.ball_age,
            'intro':request.user.intro,
            'last_login':request.user.last_login,
            'date_joined':request.user.date_joined
        }
        return JsonResponse({'code':0,'errmsg':'ok','info_data':info_data})



from apps.users.models import Address
class AddressCreateView(LoginRequiredJsonMixin,View):

    def post(self,request):
        # 1.接收请求
        data=json.loads(request.body.decode())
        # 2.获取参数，验证参数
        receiver=data.get('receiver')
        province_id=data.get('province_id')
        city_id=data.get('city_id')
        district_id=data.get('district_id')
        place=data.get('place')
        mobile=data.get('mobile')
        tag=data.get('tag')
        user=request.user
        # 验证参数 （省略）
        # 2.1 验证必传参数
        # 2.2 省市区的id 是否正确
        # 2.3 详细地址的长度
        # 2.4 手机号
        # 2.5 固定电话
        # 2.6 邮箱

        # 3.数据入库
        address=Address.objects.create(
            user=user,
            title=receiver,
            receiver=receiver,
            province_id=province_id,
            city_id=city_id,
            district_id=district_id,
            place=place,
            mobile=mobile,
            tag=tag
        )

        address_dict = {
            'id':address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
        }

        # 4.返回响应
        return JsonResponse({'code':0,'errmsg':'ok','address':address_dict})

class AddressView(LoginRequiredJsonMixin,View):

    def get(self,request):
        # 1.查询指定数据
        user=request.user
        # addresses=user.addresses

        addresses=Address.objects.filter(user=user,is_deleted=False)
        # 2.将对象数据转换为字典数据
        address_list=[]
        for address in addresses:
            address_list.append({
                "id": address.id,
                "title": address.title,
                "name": address.receiver,
                "province": address.province.name,
                "city": address.city.name,
                "district": address.district.name,
                "place": address.place,
                "tel": address.mobile,
                "address":address.province.name+address.city.name+address.district.name+address.place,
            })
        # 3.返回响应
        return JsonResponse({'code':0,'errmsg':'ok','addresses':address_list})
class historyView(LoginRequiredJsonMixin,View):
    def post(self,request):
        user=request.user
        data=json.loads(request.body.decode())
        sku_id=data.get('sku_id')
        try:
            sku=SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return JsonResponse({'code':400,'errmsg':'没有此商品'})
        redis_cli=get_redis_connection('history')
        try:
            redis_cli.lrem('history_%s'%user.id, sku_id)
        except:
            pass
        redis_cli.lpush('history_%s' % user.id, sku_id)
        redis_cli.ltrim('history_%s' % user.id,0,4)
        return JsonResponse({'code':0,'errsmg':'ok'})
    def get(self,request):
        # 1. 连接redis
        redis_cli=get_redis_connection('history')
        # 2. 获取redis数据（[1,2,3]）
        ids=redis_cli.lrange('history_%s'%request.user.id,0,4)
        # [1,2,3]
        # 3. 根据商品id进行数据查询
        history_list=[]
        for sku_id in ids:
            sku=SKU.objects.get(id=sku_id)
            # 4. 将对象转换为字典
            history_list.append({
                'id':sku.id,
                'name':sku.name,
                'default_image_url': sku.default_image.url,
                'price': sku.price
            })

        # 5. 返回JSON
        return JsonResponse({'code':0,'errmsg':'ok','skus':history_list})

